#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import base64
import pytest
import os
import allure
from py.xml import html
from config.conf import cm
from selenium import webdriver
# from appium import webdriver as appium_webdriver
from common.readconfig import ini
from tools.times import timestamp
from py._xmlgen import html
from page_object.webpage import WebPage
from tools.send_mail import send_report
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import common.globalvar as glovalvarparam

ip = glovalvarparam.get_value('ip')
url = 'http://' +ip+ ':4444/wd/hub'

driver = None
app_driver = None
@pytest.fixture(scope='session', autouse=False)
def drivers(request):
    global driver
    if driver is None:
        # driver = webdriver.Chrome()
        # driver = webdriver.Remote('http://10.10.19.140:4444/wd/hub',desired_capabilities=DesiredCapabilities.CHROME)
        driver = webdriver.Remote(url,desired_capabilities=DesiredCapabilities.CHROME)
        web = WebPage(driver)

    def fn():
        driver.quit()
    request.addfinalizer(fn)
    return web

# @pytest.fixture(scope='session', autouse=False)
# def app_drivers(request):
#     global app_driver
#     if app_driver is None:
#         desired_caps = {'platformName': 'Android',  # 平台名称
#                         'platformVersion': '7.1.2',  # 系统版本号
#                         'deviceName': '127.0.0.1:59865',  # 设备名称。如果是真机，在'设置->关于手机->设备名称'里查看
#                         'appPackage': 'com.hrss.jzsz',  # apk的包名
#                         'appActivity': 'com.hrss.jzsz.MainActivity'  # activity 名称
#                         }
#
#         # desired_caps = {'platformName': 'Android',  # 平台名称
#         #                 'platformVersion': '6.0.1',  # 系统版本号
#         #                 'deviceName': 'MuMu',  # 设备名称。如果是真机，在'设置->关于手机->设备名称'里查看
#         #                 "app": 'D:\pro\jzsz-app-v1.8.61b-release (1).apk',  # apk的包名
#         #                 'autoGrantPermissions': True  # activity 名称
#         #                 }
#
#         app_driver = appium_webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)  # 连接Appium
#         app_page = WebPage(app_driver)
#
#     def fn():
#         app_driver.quit()
#     request.addfinalizer(fn)
#     return app_page


@pytest.hookimpl(hookwrapper=True)
# def pytest_runtest_makereport(item: object) -> object:
def pytest_runtest_makereport(item) :
    """
    当测试失败的时候，自动截图，展示到html报告中
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            screen_img = _capture_screenshot()
            if screen_img:
                html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:1024px;height:768px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % screen_img
                extra.append(pytest_html.extras.html(html))
        report.extra = extra
        report.description = str(item.function.__doc__)

@pytest.hookimpl(hookwrapper=True)
def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('用例名称'))
    cells.insert(2, html.th('Test_nodeid'))
    cells.pop(2)

@pytest.hookimpl(hookwrapper=True)
def pytest_html_results_table_row(report, cells):
    cells.insert(1, html.td(report.description))
    cells.insert(2, html.td(report.nodeid))
    cells.pop(2)

@pytest.hookimpl(hookwrapper=True)
def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(html.div('通过的用例未捕获日志输出.', class_='empty log'))

#
# def pytest_html_report_title(report):
#     report.title = "就在苏州主流程自动化测试报告"
#
#
# def pytest_configure(config):
#     config._metadata.clear()
#     config._metadata['测试项目'] = "就在苏州"
#     config._metadata['测试地址'] = ini.url
#
#
# def pytest_html_results_summary(prefix, summary, postfix):
#     # prefix.clear() # 清空summary中的内容
#     prefix.extend([html.p("所属部门: 江苏云坤技术开发部")])
#     prefix.extend([html.p("测试执行人: XXX")])


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """收集测试结果"""
    result = {
        "total": terminalreporter._numcollected,
        'passed': len(terminalreporter.stats.get('passed', [])),
        'failed': len(terminalreporter.stats.get('failed', [])),
        'error': len(terminalreporter.stats.get('error', [])),
        'skipped': len(terminalreporter.stats.get('skipped', [])),
        # terminalreporter._sessionstarttime 会话开始时间
        'total times': timestamp() - terminalreporter._sessionstarttime
    }
    print(result)
    if result['failed'] or result['error']:
        pass
        # send_report()

# def pytest_sessionfinish(session):
#     pass
    # with open("{}/report/environment.properties".format(session.config.rootdir), "w") as f:
    #     f.write("browser=chrome\nbackend=staging\ndomain=http://baidu.com")


def _capture_screenshot():
    """截图保存为base64"""
    now_time, screen_path = cm.screen_file
    """webdriver remote中不支持save_screenshot"""
    if driver is None:
        app_driver.save_screenshot(screen_path)
    else:
        driver.save_screenshot(screen_path)
    allure.attach.file(screen_path, "测试失败截图...{}".format(
        now_time), allure.attachment_type.PNG)
    with open(screen_path, 'rb') as f:
        imagebase64 = base64.b64encode(f.read())
    return imagebase64.decode()